package civilian;

import jade.core.Agent;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import jade.lang.acl.UnreadableException;
import jade.proto.AchieveREInitiator;

import java.io.IOException;

import path.DistanceList;
import building.Cell;

public class SendFinishLoad {

	/**
	 * Send to Evacuators to inform they arrived at the door in their floor
	 */
	public void addBehaviour(Agent agent, DistanceList content)
			throws IOException {

		ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF);
		msg.setProtocol(agents.UtilsAgents.PROTOCOL_QUERY);
		msg.setContentObject(content);
		msg.setSender(agent.getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType(agents.UtilsAgents.EVACUATOR_AGENT);
		msg.addReceiver(agents.UtilsAgents.searchAgent(agent, sd));
		agent.addBehaviour(new SendFinishL(agent, msg));
	}

	public Cell blockingMessage(Agent agent, Cell content) throws IOException,
			UnreadableException {
		Cell cell = new Cell(Cell.FREE);

		try {
			ACLMessage msg = new ACLMessage(ACLMessage.QUERY_REF);
			msg.setProtocol(agents.UtilsAgents.PROTOCOL_QUERY);
			msg.setContentObject(content);
			msg.setSender(agent.getAID());
			ServiceDescription sd = new ServiceDescription();
			sd.setType(agents.UtilsAgents.EVACUATOR_AGENT);
			msg.addReceiver(agents.UtilsAgents.searchAgent(agent, sd));
			agent.send(msg);

			MessageTemplate mt1 = MessageTemplate
					.MatchPerformative(ACLMessage.AGREE);// no lo esta
															// hacient777
			MessageTemplate mt2 = MessageTemplate
					.MatchProtocol(agents.UtilsAgents.PROTOCOL_QUERY);
			ACLMessage msg2 = agent.blockingReceive(MessageTemplate.and(mt1,
					mt2));
			cell = (Cell) msg2.getContentObject();
			System.out.println("Civilian:I arrived to door sendfinishload");
		} catch (Exception e) {
			System.out.println("send finish load" + e.toString());
		}
		System.out.println("Termino" + cell);

		return cell;

	}

	public class SendFinishL extends AchieveREInitiator {
		/**
         *
         */
		private static final long serialVersionUID = 1L;

		public SendFinishL(Agent arg0, ACLMessage arg1) {
			super(arg0, arg1);
		}

		/**
		 * Receive agree from the evacuator, and the content is the cell of the
		 * recycling center
		 */
		@Override
		protected void handleAgree(ACLMessage msg) {
			Cell cell = null;
			try {
				cell = (Cell) msg.getContentObject();

			} catch (UnreadableException e) {
				e.printStackTrace();
			}
			System.out.println("Receive from Evacuator, cell x: "
					+ cell.getColumn() + ", cell y: " + cell.getRow()
					+ "cell floor" + cell.getFloor());
		}

		/**
		 * Receive refuse from the evacuator. The content is null.
		 */
		@Override
		protected void handleRefuse(ACLMessage arg0) {
			System.out.println("From Evacuator: refuse in finish load.");
		}
	}
}
